require 'rest-client'
require 'json'

module GiteeTransfer
  class Request
    def get_projects(options = {})
      # API: '/api/v5/enterprises/{enterprise_path}/repos'
      url = "#{GiteeTransfer.config.gitee_host}/api/v5/enterprises/enterprise/repos"
      GiteeTransfer.logger.info "Get projects url: #{url}"
      headers = {
        params: {
          access_token: GiteeTransfer.config.gitee_access_token,
          type: 'all',
          page: options[:page] || 1,
          per_page: 20
        }
      }
      GiteeTransfer.logger.info "Get projects headers: #{headers}"
      response = RestClient.get(url, headers)
      # GiteeTransfer.logger.info "Get projects response: #{response}"
      JSON.parse(response.body)
    rescue => ex
      GiteeTransfer.logger.error "[ERROR] Get projects error: #{ex}"
      nil
    end

    def create_project(options = {})
      # API: '/api/gitee/{enterprise_path}/dashboard/projects'
      url = "#{GiteeTransfer.config.xly_host}/api/gitee/enterprise/dashboard/projects"
      GiteeTransfer.logger.info "Create project url: #{url}"
      payload = {
        program_id: options[:program_id],
        language: options[:language],
        project: {
          name: options[:name],
          path: options[:path],
          description: options[:description],
          can_create_branch: options[:can_create_branch],
          public: 0,
          outsourced: 0
        }
      }
      GiteeTransfer.logger.info "Get projects payload: #{payload}"
      response = RestClient.post(url, payload, { 'Cookie' => GiteeTransfer.config.xly_cookie })
      GiteeTransfer.logger.info "Create project response: #{response}"
      JSON.parse(response.body)
    rescue RestClient::ExceptionWithResponse => ex
      response = JSON.parse(ex.response)
      if response['message'].end_with?('请修改仓库命名空间或仓库名。')
        GiteeTransfer.logger.info "Create project response: #{response['message']}"
        created_repo_result(response['message'])
      else
        GiteeTransfer.logger.error "[ERROR] Create project error. ex: #{ex}"
        GiteeTransfer.logger.error "[ERROR] Create project error. response: #{ex.response}"
        nil
      end
    rescue => ex
      GiteeTransfer.logger.error "[ERROR] Create project error: #{ex}"
      nil
    end

    def get_languages
      url = "#{GiteeTransfer.config.xly_host}/api/gitee/api/v3/projects/languages"
      headers = { 'Cookie' => GiteeTransfer.config.xly_cookie }
      GiteeTransfer.logger.info "Get languages url: #{url}"
      response = RestClient.get(url, headers)
      GiteeTransfer.logger.info response
      JSON.parse(response)
    end

    def set_default_branch(options = {})
      # API: /api/gitee/{namespace}/{repo}/branches/{branch}/set_default_branch
      url = "#{GiteeTransfer.config.xly_host}/api/gitee/#{options[:namespace]}/#{options[:repo_path]}/branches/#{options[:branch]}/set_default_branch"
      GiteeTransfer.logger.info "Set default branch url: #{url}"
      response = RestClient.put(url, nil, { 'Cookie' => GiteeTransfer.config.xly_cookie })
      GiteeTransfer.logger.info response
      JSON.parse(response)
    rescue => ex
      GiteeTransfer.logger.error "[ERROR] Set default branch error: #{ex}"
      nil
    end

    private

    def created_repo_result(message)
      path_with_namespace = message.split('：').last.split(',').first
      namespace_path = path_with_namespace.split('/').first
      path = path_with_namespace.split('/').last
      {
        'project' => {
          'path_with_namespace' => path_with_namespace,
          'namespace_path' => namespace_path,
          'path' => path
        }
      }
    end
  end
end
